﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

//打印链表
void SLTPrint(SLTNode* phead)
{
	SLTNode* pur = phead;
	while (pur)
	{
		printf("%d->", pur->data);
		pur = pur->next;
	}
	printf("NULL\n");
}
//申请新节点
SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* node = (SLTNode*)malloc(sizeof(SLTNode));
	if (node == NULL)
	{
		perror("malloc");
		return NULL;
	}
	node->data = x;
	node->next = NULL;
	return node;
}
//尾插数据
void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newNode = SLTBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newNode;

	}
	else
	{
		SLTNode* pur = *pphead;
		while (pur->next)
		{
			pur = pur->next;
		}
		pur->next = newNode;
	}
}
//头插数据
void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newNode = SLTBuyNode(x);
	newNode->next = *pphead;
	*pphead = newNode;
}
//尾删
void SLTPopBack(SLTNode** pphead)
{
	SLTNode* pur = *pphead;
	SLTNode* prev = NULL;
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		while (pur->next)
		{
			prev = pur;
			pur = pur->next;
		}
		prev->next = NULL;
		free(pur);
		pur = NULL;
	}
	
}
//头删
void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* phead = (*pphead)->next;
	free(*pphead);
	*pphead = phead;
}
//查找
SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	SLTNode* pur = phead;
	while (pur)
	{
		if (pur->data == x)
		{
			return pur;
		}
		pur = pur->next;
	}
}
//在指定位置之前插⼊数据
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead && pos);
	if (pos == *pphead)
	{
		SLTPushFront(pphead, x);//要传pphead,不能传*pphead
		/*SLTNode* newNode = SLTBuyNode(x);
		newNode->next = *pphead;
		*pphead = newNode;*/
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		SLTNode* newNode = SLTBuyNode(x);
		newNode->next = pos;
		prev->next = newNode;
	}
}
//在指定位置之后插⼊数据
void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	SLTNode* newNode = SLTBuyNode(x);
	newNode->next = pos->next;
	pos->next = newNode;
}
//删除pos结点
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	if (pos == *pphead)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
//删除pos之后的结点
void SLTEraseAfter(SLTNode* pos)
{
	assert(pos && pos->next);
	SLTNode* pur = pos->next;
	pos->next = pos->next->next;
	free(pur);
	pur = NULL;
}
//销毁链表
void SListDestroy(SLTNode** pphead)
{
	SLTNode* pur = *pphead;
	while (pur)
	{
		SLTNode* next = pur->next;
		free(pur);
		pur = next;
	}
}